<template>
    <view class="date-picker-overlay" v-if="visible" @click="onOverlayClick">
        <view class="date-picker" :class="{ 'dark': isDarkMode }" :style="themeStyle" @click.stop>
            <!-- 头部 -->
            <view class="picker-header">
                <text class="header-title">{{ title }}</text>
                <text class="close-btn bigfont big-guanbi" @click="onClose"></text>
            </view>

            <!-- 选择器主体 -->
            <view class="picker-body">
                <!-- 年份选择 -->
                <view class="picker-column">
                    <view class="column-title">年份</view>
                    <view class="picker-content">
                        <view class="picker-mask top"></view>
                        <view class="picker-indicator"></view>
                        <view class="picker-mask bottom"></view>
                        <swiper class="swiper-container" :vertical="true" :circular="false" @change="onYearChange"
                            :display-multiple-items="5" :current="yearIndex">
                            <swiper-item v-for="year in years" :key="year" class="swiper-item">
                                <view class="picker-item"
                                    :class="{ 'selected': year === selectedYear, 'empty': !year }">
                                    {{ year ? `${year}年` : '' }}
                                </view>
                            </swiper-item>
                        </swiper>
                    </view>
                </view>

                <!-- 月份选择 -->
                <view class="picker-column">
                    <view class="column-title">月份</view>
                    <view class="picker-content">
                        <view class="picker-mask top"></view>
                        <view class="picker-indicator"></view>
                        <view class="picker-mask bottom"></view>
                        <swiper class="swiper-container" :vertical="true" :circular="false" @change="onMonthChange"
                            :display-multiple-items="5" :current="monthIndex">
                            <swiper-item v-for="month in months" :key="typeof month === 'string' ? month : month.value"
                                class="swiper-item">
                                <view class="picker-item" :class="{
                                    'selected': typeof month === 'object' && month.value === selectedMonth,
                                    'empty': typeof month === 'string',
                                    'disabled': typeof month === 'object' && month.disabled
                                }">
                                    {{ typeof month === 'object' ? `${month.value}月` : '' }}
                                </view>
                            </swiper-item>
                        </swiper>
                    </view>
                </view>
            </view>

            <!-- 底部按钮 -->
            <view class="picker-footer">
                <button class="btn cancel-btn" @click="onCancel">取消</button>
                <button class="btn confirm-btn" @click="onConfirm">确定</button>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { currentTheme, isDarkMode, themes } from '@/store/theme';
import { computed, nextTick, onMounted, ref, watch } from 'vue';

// 定义月份对象的接口
interface MonthItem {
    value: number;
    disabled: boolean;
}

type MonthType = MonthItem | string;

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: '选择日期'
    },
    defaultYear: {
        type: Number,
        default: null
    },
    defaultMonth: {
        type: Number,
        default: null
    },
    minYear: {
        type: Number,
        default: 2020
    },
    maxYear: {
        type: Number,
        default: 2030
    },
    disablePastMonths: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['update:visible', 'confirm', 'cancel'])

// 导出函数供外部使用
const exposed = {
    isDateDisabled: (year: number, month: number) => {
        if (!props.disablePastMonths) return false

        const currentDate = new Date()
        const currentYear = currentDate.getFullYear()
        const currentMonth = currentDate.getMonth() + 1

        // 如果是当前年份，则禁用小于当前月份的月份
        if (year === currentYear) {
            return month < currentMonth
        }

        // 其他年份都可选
        return false
    }
}

defineExpose(exposed)

// 状态管理
const selectedYear = ref(props.defaultYear || new Date().getFullYear())
const selectedMonth = ref<number>(props.defaultMonth || new Date().getMonth() + 1)
const initialYear = ref(new Date().getFullYear())
const initialMonth = ref(new Date().getMonth() + 1)
console.log(selectedYear.value, selectedMonth.value)
const yearIndex = ref(0)
const monthIndex = ref(0)
const itemHeight = 80 // rpx
const touching = ref(false)

// 计算属性
const years = computed(() => {
    const years = []
    // 添加2个空白项在开头
    years.push('', '')
    for (let i = props.minYear; i <= props.maxYear; i++) {
        years.push(i)
    }
    // 添加2个空白项在结尾
    years.push('', '')
    return years
})

const months = computed(() => {
    const months: MonthType[] = []
    // 添加2个空白项在开头
    months.push('', '')
    for (let i = 1; i <= 12; i++) {
        // 只在初始年份中判断月份是否禁用
        const isDisabled = selectedYear.value === initialYear.value && i < initialMonth.value
        months.push({
            value: i,
            disabled: isDisabled
        })
    }
    // 添加2个空白项在结尾
    months.push('', '')
    return months
})

// 主题相关
const themeColors = computed(() => {
    const theme = themes.find(t => t.id === currentTheme.value)
    return theme ? theme.colors : themes[0].colors
})

const toRGBA = (hex: string, alpha: number) => {
    const r = parseInt(hex.slice(1, 3), 16)
    const g = parseInt(hex.slice(3, 5), 16)
    const b = parseInt(hex.slice(5, 7), 16)
    return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

const themeStyle = computed(() => ({
    '--theme-primary': themeColors.value.primary,
    '--theme-primary-alpha': toRGBA(themeColors.value.primary, 0.15),
    '--theme-bg': isDarkMode.value ? '#1a1a1a' : '#ffffff',
    '--theme-text': isDarkMode.value ? '#ffffff' : '#333333',
    '--theme-text-secondary': isDarkMode.value ? '#b0b0b0' : '#666666',
    '--theme-border': isDarkMode.value ? '#404040' : '#e0e0e0',
    '--theme-mask': isDarkMode.value ? 'rgba(0, 0, 0, 0.85)' : 'rgba(0, 0, 0, 0.6)'
}))

// 方法
const onOverlayClick = () => {
    emit('update:visible', false)
}

const onClose = () => {
    emit('update:visible', false)
}

const onYearChange = (e: any) => {
    const currentIndex = e.detail.current
    const year = years.value[currentIndex + 2]
    if (typeof year === 'number') {
        selectedYear.value = year
    }
}

const onMonthChange = (e: any) => {
    const currentIndex = e.detail.current
    const month = months.value[currentIndex + 2]
    if (typeof month === 'object' && 'value' in month && !month.disabled) {
        selectedMonth.value = month.value
    }
}

const onConfirm = () => {
    emit('confirm', {
        year: selectedYear.value,
        month: selectedMonth.value
    })
    emit('update:visible', false)
}

// 监听默认值变化
watch(() => props.defaultYear, (newVal) => {
    if (newVal) {
        selectedYear.value = newVal
        // 因为数组前面添加了两个空白项，所以实际索引需要减2
        const yearIdx = years.value.indexOf(newVal)
        if (yearIdx > -1) {
            yearIndex.value = yearIdx - 2
        }
    }
}, { immediate: true })

watch(() => props.defaultMonth, (newVal) => {
    if (newVal) {
        selectedMonth.value = newVal
        // 因为数组前面添加了两个空白项，所以实际索引需要减2
        const monthIdx = months.value.findIndex(m =>
            typeof m === 'object' && m.value === newVal && !exposed.isDateDisabled(selectedYear.value, newVal)
        )
        if (monthIdx > -1) {
            monthIndex.value = monthIdx - 2
        }
    }
}, { immediate: true })

// 重置为默认值或当前日期
const resetToDefault = () => {
    const defaultYear = props.defaultYear || new Date().getFullYear()
    const defaultMonth = props.defaultMonth || new Date().getMonth() + 1

    selectedYear.value = defaultYear
    selectedMonth.value = defaultMonth

    // 设置正确的索引位置
    const yearIdx = years.value.indexOf(defaultYear)
    const monthIdx = months.value.findIndex(m =>
        typeof m === 'object' && m.value === defaultMonth
    )

    if (yearIdx > -1) {
        yearIndex.value = yearIdx - 2
    }
    if (monthIdx > -1) {
        monthIndex.value = monthIdx - 2
    }
}

// 取消时重置为默认值
const onCancel = () => {
    resetToDefault()
    emit('cancel')
    emit('update:visible', false)
}

// 组件挂载时初始化
onMounted(() => {
    nextTick(() => {
        resetToDefault()
    })
})
</script>

<style scoped>
.date-picker-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--theme-mask);
    z-index: 999;
    display: flex;
    align-items: flex-end;
    transition: all 0.3s ease;
    backdrop-filter: blur(8rpx);
}

.date-picker {
    width: 100%;
    background-color: var(--theme-bg);
    border-radius: 24rpx 24rpx 0 0;
    overflow: hidden;
    transform: translateY(0);
    transition: all 0.3s ease;
    box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.12);
}

.picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    border-bottom: 2rpx solid var(--theme-border);
    background-color: var(--theme-bg);
}

.header-title {
    font-size: 32rpx;
    font-weight: 600;
    color: var(--theme-text);
}

.close-btn {
    font-size: 48rpx;
    color: var(--theme-text-secondary);
    padding: 0 20rpx;
}

.picker-body {
    display: flex;
    height: 480rpx;
    padding: 20rpx 0;
}

.picker-column {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.column-title {
    text-align: center;
    font-size: 28rpx;
    color: var(--theme-text-secondary);
    padding: 20rpx 0;
}

.picker-content {
    flex: 1;
    position: relative;
    height: 400rpx;
    overflow: hidden;
}

.swiper-container {
    height: 400rpx;
    width: 100%;
}

.swiper-item {
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.picker-item {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 32rpx;
    color: var(--theme-text-secondary);
    opacity: 0.8;
    transition: all 0.3s ease;
    transform: scale(0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    letter-spacing: 1px;
}

.picker-item.selected {
    color: var(--theme-text);
    opacity: 1;
    transform: scale(1.1);
    font-weight: normal;
    letter-spacing: 1px;
    text-shadow: none;
}

.picker-item.empty {
    opacity: 0;
    pointer-events: none;
}

.picker-item.disabled {
    color: var(--theme-text-secondary);
    opacity: 0.4;
    pointer-events: none;
}

.picker-mask {
    position: absolute;
    left: 0;
    right: 0;
    height: 160rpx;
    pointer-events: none;
    z-index: 2;
    background-color: var(--theme-bg);
    opacity: 0.95;
}

.picker-mask.top {
    top: 0;
    background: linear-gradient(to bottom, var(--theme-bg), rgba(255, 255, 255, 0));
}

.picker-mask.bottom {
    bottom: 0;
    background: linear-gradient(to top, var(--theme-bg), rgba(255, 255, 255, 0));
}

.picker-indicator {
    position: absolute;
    left: 24rpx;
    right: 24rpx;
    top: 160rpx;
    height: 80rpx;
    pointer-events: none;
    z-index: 1;
    background-color: var(--theme-primary-alpha);
    border-radius: 12rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.picker-footer {
    display: flex;
    padding: 20rpx 32rpx;
    border-top: 2rpx solid var(--theme-border);
    background-color: var(--theme-bg);
}

.btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 40rpx;
    font-size: 32rpx;
    margin: 0 12rpx;
    transition: all 0.2s ease;
    font-weight: normal;
}

.cancel-btn {
    background-color: #f5f5f5;
    color: var(--theme-text);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.confirm-btn {
    background-color: var(--theme-primary);
    color: #ffffff;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.btn:active {
    opacity: 0.8;
    transform: scale(0.98);
}

/* 暗色模式下的特殊处理 */
.dark .date-picker {
    box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.3);
    border-top: 2rpx solid rgba(255, 255, 255, 0.1);
}

.dark .cancel-btn {
    background-color: rgba(255, 255, 255, 0.1);
    box-shadow: none;
}

.dark .picker-indicator {
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.2);
}
</style>